package exer1;

import org.junit.Test;

import java.io.UnsupportedEncodingException;

/**
 * Date:2025/2/23
 * Author：zhouzhou
 * Description:
 */
public class String_Method {
    @Test
    public void test1() {
        int num = 2;
        //基本数据类型 ---->String
        //1.
        String s1 = num + "";
        //2.
        String s2 = String.valueOf(num);

        //String --->基本数据类型
        String s3 = "123";
        int i1 = Integer.parseInt(s1);
    }

    //String与char[]之间的转换
    @Test
    public void test2() {
        String str = "hello";
        //String---->char[]
        char[] arr = str.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        //char[]--->String
        String str1 = new String(arr);
        System.out.println(str1);
    }

    /**
     * String与byte[]之间的转换(难度)
     */
    @Test
    public void test3() throws UnsupportedEncodingException {
        //String --->byte[]
        //gbk utf-8 兼容ASCII
        String str=new String("abcdefg");//1个字母占1个byte
        str="abc中国";
        byte[] bytes=str.getBytes();//该方法使用默认字符集(utf-8 设置)  3个byte 等于1个汉字
        byte[] bytes1 = str.getBytes("gbk");//1个汉字占2byte
        for (byte i : bytes1) {
            System.out.println(i);
        }

        //byte[]--->String
        String str2 = new String(bytes);
//        String str3 = new String(bytes,"gbk");//解码使用gbk,出现乱码,当初默认编码为utf-8
        System.out.println(str2);
    }
}
